<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item prop="unknown" style="width: 360px;margin-top: 30px;" class="search-input-wrap">
        <el-input placeholder="搜索内容" v-model="queryParams.unknown" class="input-with-select" :style="{ width: '100%' }">
          <el-select v-model="select" slot="prepend" placeholder="请选择" :style="{ width: '100px' }">
            <el-option label="申请单号" value="1" />
            <el-option label="采购单号" value="2" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="handleQuery" />
        </el-input>
      </el-form-item>

      <el-form-item label="制单日期" style="width: 350px">
        <el-date-picker v-model="queryParams.applicationTime" value-format="yyyy-MM-dd" type="daterange" align="right"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" />
      </el-form-item>

      <el-form-item label="退款单状态" style="width: 180px">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择退款单状态" clearable style="width: 100%">
          <el-option
            v-for="dict in dict.type.request_payment_status.filter(item => ['4', '5', '6', '7'].includes(item.value))"
            :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" style="width: 180px">
        <el-select v-model="queryParams.paymentReviewStatus" placeholder="请选择审核状态" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.payment_review_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-top: 30px;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="PaymentReturnList" ref="parentTable" row-key="paymentRequestId"
      @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center" />

      <el-table-column align="center" width="20" type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.items">
            <el-table-column label="图片" prop="imageUrl" align="center" width="80">
              <template slot-scope="scope">
                <div class="image-container">
                  <image-preview v-if="scope.row.imageUrl" :src="scope.row.imageUrl" :width="50" :height="50"
                    class="image-item" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="产品名称" align="center" prop="productName" />
            <el-table-column label="SKU" align="center" prop="sku" />
            <el-table-column label="退款数量" align="center" prop="quantity" />
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="退款单号" align="center" prop="paymentRequestCode" />
      <el-table-column label="采购单号" align="center" prop="ordersNumber" />
      <el-table-column label="审核状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_review_status" :value="scope.row.paymentReviewStatus" />
        </template>
      </el-table-column>
      <el-table-column label="退款方式" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.request_payment_type" :value="scope.row.paymentType" />
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center">
        <template v-slot="scope">
          {{ scope.row.returnAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="退款单状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.request_payment_status" :value="scope.row.paymentStatus" />
        </template>
      </el-table-column>
      <el-table-column label="制单" align="center" width="155">
        <template slot-scope="scope">
          {{ scope.row.applicant }}<br />
          {{ formatDate(scope.row.applicationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="收款标记状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_mark_status" :value="scope.row.returnStatus" />
        </template>
      </el-table-column>
      <el-table-column label="收款单图片" prop="imagePath" align="center">
        <template slot-scope="scope">
          <div class="image-container">
            <image-preview v-if="scope.row.returnImage" :src="scope.row.returnImage" :width="50" :height="50"
              class="image-item" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
            'finance:paymentReturn:approved',
            'finance:paymentReturn:reject',
            'finance:paymentReturn:posting',
            'finance:paymentReturn:mark',
          ]">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="approvedQuash" icon="el-icon-check"
                v-hasPermi="['finance:paymentReturn:approved']"
                v-if="scope.row.paymentReviewStatus == 0 && scope.row.reviewerUserId == userId">核准</el-dropdown-item>
              <el-dropdown-item command="rejectQuash" icon="el-icon-close" v-hasPermi="['finance:paymentReturn:reject']"
                v-if="scope.row.paymentReviewStatus == 0 && scope.row.reviewerUserId == userId">驳回</el-dropdown-item>
              <el-dropdown-item command="markQuash" icon="el-icon-bell" v-hasPermi="['finance:paymentReturn:mark']"
                v-if="scope.row.paymentReviewStatus == 1 && scope.row.reviewerUserId == userId">标记已收款</el-dropdown-item>
              <el-dropdown-item command="uploadQuash" icon="el-icon-finished"
                v-hasPermi="['finance:paymentReturn:posting']"
                v-if="scope.row.paymentReviewStatus == 1 && scope.row.reviewerUserId == userId">上传收款单</el-dropdown-item>
              <el-dropdown-item command="LogQuash" icon="el-icon-s-operation">日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column label="退款备注" align="center" prop="returnRemark" width="120px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.returnRemark">
            <span>
              {{ scope.row.returnRemark && scope.row.returnRemark.length > 5 ? scope.row.returnRemark.slice(0, 5)
                + '...' : (scope.row.returnRemark || '-') }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getPaymentReturnList" />

    <!-- 审核日志记录 -->
    <el-dialog :visible.sync="openLog" width="1400px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="PaymentRequestLogList" height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
        <el-table-column label="审核状态" align="center" prop="logStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.process_status" :value="scope.row.logStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center" prop="logApplicant" />
        <el-table-column label="审核时间" align="center" prop="logTime" />
        <el-table-column label="审核备注" align="center" prop="logRemark" />
        <el-table-column label="申请人" align="center" prop="applicant" />
        <el-table-column label="申请时间" align="center" prop="applicationTime" />
      </el-table>

      <pagination v-show="logTotals > 0" :total="logTotals" :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize" @pagination="getPaymentRequestLogList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRequestLog">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="上传信息" :visible.sync="dialogVisible">
      <!-- 新增：显示 row.items 的数据 -->
      <div v-if="currentRow.items && currentRow.items.length">
        <h4>商品信息</h4>
        <el-table :data="currentRow.items" border style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="sku" label="SKU" />
          <el-table-column prop="quantity" label="退货数量" />
        </el-table>
      </div>

      <!-- 已有上传区域 -->
      <el-form ref="form" :model="formUpload" :rules="rules" label-width="80px">
        <el-upload class="upload-demo" ref="upload" :limit="1" accept=".jpg, .png" :action="upload.url"
          :headers="upload.headers" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
          :file-list="upload.fileList" list-type="picture" :auto-upload="false">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sumbitUpload" :loading="isSubmitting" :disabled="isSubmitting">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import {
  listPaymentReturn, //数据列表
  uploadReturnImage, //上传收款单
  setPaymentRequestMark,//标记已收款
} from "@/api/finance/paymentReturn";
import { updateProcessStatus, selectPaymentRequestLogList } from "@/api/orders/ProcuredOrders";
import Treeselect from "@riophae/vue-treeselect";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "paymentReturn",
  dicts: [
    "request_payment_status",
    "request_payment_type",
    "payment_review_status",
    "process_status",
    "payment_mark_status"
  ],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      select: "1",
      // 总条数
      total: 0,
      // 付款单表格数据
      PaymentReturnList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationTime: this.getLastMonthRange(),
        deleteStatus: '0',
        paymentStatus: null,
      },
      selectedRows: [], // 存储选中的行数据
      PymentRequestProcessParams: {
        paymentRequestId: "",
        processStatus: "",
        reviewerId: "",
        processRemark: "",
      },
      //当前用户id
      userId: store.getters.userId,
      openLog: false,
      PaymentRequestLogList: [],
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,
      //上传收款单
      currentRow: {}, // 当前选中的行数据
      dialogVisible: false,
      formUpload: {
        paymentRequestId: [],
        returnImage: null,
        procuredOrderId: null,

      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      // 防止重复提交
      isSubmitting: false,
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getPaymentReturnList();
  },
  computed: {
  },
  methods: {
    /** 查询付款单列表 */
    getPaymentReturnList() {
      this.loading = true;
      let startTime, endTime;

      // 确保正确处理日期格式
      if (this.queryParams.applicationTime && this.queryParams.applicationTime.length === 2) {
        // 如果是 Date 对象，转换为字符串
        if (this.queryParams.applicationTime[0] instanceof Date) {
          startTime = this.formatDateToString(this.queryParams.applicationTime[0]);
          endTime = this.formatDateToString(this.queryParams.applicationTime[1]);
        } else {
          // 如果已经是字符串，直接使用
          [startTime, endTime] = this.queryParams.applicationTime;
        }
      }

      this.queryParams.reviewerUserId = this.userId;
      const params = {
        ...this.queryParams,
        startTime,
        endTime,
      };
      console.info(params);
      delete params.applicationTime;
      listPaymentReturn(params).then((response) => {
        this.PaymentReturnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.select = this.select;
      this.getPaymentReturnList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getLastMonthRange() {
      const endDate = new Date(); // 当前时间
      const startDate = new Date();
      startDate.setMonth(startDate.getMonth() - 3); // 设置为三个月
      return [startDate, endDate];
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.ids = selection.map((item) => item.paymentRequestId);
      this.multiple = !this.selectedRows.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "approvedQuash":
          this.sumbitReturn(row, '1');
          break;
        case "rejectQuash":
          this.handleReject(row, '2');
          break;
        case "uploadQuash":
          this.showUpload(row);
          break;
        case "LogQuash":
          this.paymentRequestLog(row);
          break;
        case "markQuash":
          this.paymentRequestMark(row);
          break;
        default:
          break;
      }
    },
    // 核准
    sumbitReturn(selectRow, processStatus, processRemark = '') {

      this.PymentRequestProcessParams.paymentRequestId = selectRow.paymentRequestId;
      this.PymentRequestProcessParams.processStatus = processStatus;
      this.PymentRequestProcessParams.reviewerId = this.userId;
      this.PymentRequestProcessParams.processRemark = processRemark;
      this.PymentRequestProcessParams.paymentType = selectRow.paymentType;
      this.PymentRequestProcessParams.items = selectRow.items;

      let title = processStatus == 1 ? "同意审批" : "拒绝审批";

      // 只有核准时才显示确认弹窗，驳回直接执行
      const executeUpdate = () => {
        return Promise.resolve()
          .then(() => {
            return updateProcessStatus(this.PymentRequestProcessParams);
          })
          .then(() => {
            this.getPaymentReturnList();
            this.$modal.msgSuccess(title);
          })
          .catch(() => { });
      };

      if (processStatus == 1) {
        // 核准需要确认
        this.$modal
          .confirm(selectRow.paymentRequestCode + "，您确认所选数据将核准吗？")
          .then(() => executeUpdate())
          .catch(() => { });
      } else {
        // 驳回直接执行
        executeUpdate();
      }
    },
    //驳回
    handleReject(row, processStatus) {
      this.$prompt('请输入驳回原因：', '驳回审批', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputErrorMessage: '驳回原因不能为空'
      }).then(({ value }) => {
        this.sumbitReturn(row, processStatus, value);
      }).catch(() => {
        this.$message.info('已取消驳回操作');
      });
    },
    //标记已收款
    paymentRequestMark(row) {
      const executeUpdate = () => {
        return Promise.resolve()
          .then(() => {
            return setPaymentRequestMark(row.paymentRequestId);
          })
          .then(() => {
            this.getPaymentReturnList();
            this.$modal.msgSuccess("标记已收款成功");
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
      };

      this.$modal
        .confirm(row.paymentRequestCode + "，您确认所选数据将标记为已收款吗")
        .then(() => executeUpdate())
        .catch(() => { });
    },
    //上传收款单
    showUpload(row) {
      this.currentRow = row; // 存储选中的数据
      this.dialogVisible = true;
      this.formUpload.paymentRequestId = row.paymentRequestId;
      this.formUpload.procuredOrderId = row.procuredOrderId;
    },
    //查审核日志
    paymentRequestLog(row) {
      this.openLog = true;
      this.logParam.paymentRequestId = row.paymentRequestId;
      this.getPaymentRequestLogList();
    },
    //查询所有的申请记录
    getPaymentRequestLogList() {
      this.loading = true;
      selectPaymentRequestLogList(this.logParam).then((response) => {
        this.PaymentRequestLogList = response.rows;
        this.logTotals = response.rows.length;
        this.loading = false;
      });
    },
    cancelRequestLog() {
      this.openLog = false;
    },
    /** 上传水单确认按钮 */
    async sumbitUpload() {
      if (this.isSubmitting) {
        this.$message.error("数据正在处理，请勿重复提交！");
        return;
      }

      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.isSubmitting = true; // 设置提交状态
          try {
            // 手动触发上传，并等待完成
            await this.uploadFile();
            // 确保上传完成后再提交
            if (
              this.formUpload.paymentRequestId &&
              this.formUpload.returnImage && this.formUpload.procuredOrderId
            ) {
              await uploadReturnImage(this.formUpload);
              this.$modal.msgSuccess("上传收到款单成功！");
              this.dialogVisible = false;
              this.getPaymentReturnList();
            }
          } catch (error) {
            //this.$message.error("上传失败，请重试！");
          } finally {
            this.isSubmitting = false; // 重置提交状态
          }
        }
      });
    },
    uploadFile() {
      return new Promise((resolve, reject) => {
        this.$refs.upload.submit();
        this.$once("upload-success", resolve); // 上传成功后 resolve
        this.$once("upload-failed", reject); // 上传失败后 reject
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      // 提取 `/profile/upload/...` 之后的部分
      const fullPath = response.url;
      const relativePath = fullPath.substring(fullPath.indexOf("/profile/upload"));
      this.formUpload.returnImage = relativePath;
      // 触发上传成功事件
      this.$emit("upload-success");
    },
    //上传水单取消按钮
    cancel() {
      this.dialogVisible = false;
      this.$refs.upload.clearFiles();
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    formatDateToString(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  },
};
</script>
